package de.hauschild.jchronology;

import java.io.File;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.apache.commons.io.FilenameUtils;

public class JChronology {

  public static void main(String[] args) {
    final File chronologyFile = getChronologyFile(args);
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        new JChronologyFrame(chronologyFile);
      }
    });
  }

  private static File getChronologyFile(String[] args) {
    File chronologyFile = null;
    if (args.length == 0) {
      JFileChooser fileChooser = new JFileChooser((String) null);
      fileChooser.setFileFilter(new FileNameExtensionFilter("JChronology-Datei", "jchron"));
      if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
        chronologyFile = fileChooser.getSelectedFile();
        if (FilenameUtils.getExtension(chronologyFile.getAbsolutePath()).equals("")) {
          chronologyFile = new File(chronologyFile.getAbsoluteFile() + ".jchron");
        }
      } else {
        JOptionPane.showMessageDialog(null, "Keine JChronology-Datei gewählt.");
        System.exit(1);
      }
    } else {
      chronologyFile = new File(args[0]);
    }
    if (!chronologyFile.exists()) {
      try {
        chronologyFile.createNewFile();
      } catch (IOException e) {
        JOptionPane.showMessageDialog(null, "Kann JChronology-Datei nicht anlegen.");
        System.exit(1);
      }
    }
    return chronologyFile;
  }

}
